using Digitalmes.Domain.Entities.Mes.Equipments;
using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Equipments.Machinery.Commands;

/// <summary>
/// 设备创建命令。
/// </summary>
/// <param name="Machinery"></param>
public sealed record CreateMachineryCommand(EquipMachineryDto Machinery) : IRequest<IResult<bool>>;

internal sealed class CreateMachineryCommandHandler(IRepository<EquipMachinery> repo, IRepository<MdWorkstation> workstationRepo)
    : IRequestHandler<CreateMachineryCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateMachineryCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.MachineryCode == request.Machinery.MachineryCode, cancellationToken))
        {
            return Result.Failure("设备编号已存在");
        }

        var workstation = await workstationRepo.GetByIdAsync(request.Machinery.WorkstationId, cancellationToken);
        if (workstation == null)
        {
            return Result.Failure("指定的工位不存在");
        }

        var machinery = request.Machinery.Adapt<EquipMachinery>();
        machinery.LineId = workstation.LineId;

        var ok = await repo.InsertAsync(machinery, cancellationToken);
        return Result.From(ok);
    }
}
